package model

import (
	"errors"
	"haodayizhi/global"
	"time"

	"gorm.io/gorm"
)

const TableNameProduct = "products"

// Product mapped from table <products>
type Product struct {
	ID           int64     `gorm:"column:id;type:bigint;primaryKey;autoIncrement:true" json:"id,string"`
	Name         string    `gorm:"column:name;type:varchar(255);not null" json:"name"`
	Tags         string    `gorm:"column:tags;type:json" json:"tags"`
	ImagePaths   string    `gorm:"column:image_paths;type:json" json:"imagePaths"`
	Title        string    `gorm:"column:title;type:varchar(255)" json:"title"`
	Effects      string    `gorm:"column:effects;type:json" json:"effects"`
	Detail       string    `gorm:"column:detail;type:text" json:"detail"`
	SoldOut      int64     `gorm:"column:sold_out;type:bigint" json:"soldOut"`
	Price        float64   `gorm:"column:price;type:decimal(10,2)" json:"price"`
	DiscountRate float64   `gorm:"column:discount_rate;type:decimal(5,2)" json:"discountRate"`
	CreatedAt    time.Time `gorm:"column:created_at;comment:创建时间" json:"createdAt"`
	RemovedAt    time.Time `gorm:"column:removed_at;type:timestamp" json:"removedAt"`
	IsRemoved    int64     `gorm:"column:is_removed;type:tinyint(1)" json:"isRemoved"`
}

// TableName Product's table name
func (*Product) TableName() string {
	return TableNameProduct
}

// CreateProduct creates a new Product in the database.
func (m *Product) CreateProduct() error {
	if err := global.Db.Create(m).Error; err != nil {
		return err
	}
	return nil
}

// GetProductByID retrieves a Product by its ID from the database.
func (m *Product) GetProductByID(id int64) (*Product, error) {
	result := global.Db.First(m, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			return nil, nil // Product not found
		}
		return nil, result.Error
	}
	return m, nil
}

// UpdateProduct updates an existing Product in the database.
func (m *Product) UpdateProduct() error {
	if err := global.Db.Save(m).Error; err != nil {
		return err
	}
	return nil
}

// DeleteProduct deletes a Product by its ID from the database.
func (m *Product) DeleteProduct(id int64) error {
	if err := global.Db.Delete(m, id).Error; err != nil {
		return err
	}
	return nil
}

// 获取产品列表
func GetProductList(page, pageSize int) ([]*Product, int64, error) {
	var products []*Product
	var total int64
	result := global.Db.Offset((page - 1) * pageSize).Limit(pageSize).Find(&products)
	if result.Error != nil {
		return nil, total, result.Error
	}
	// 获取总长度
	result = global.Db.Model(&User{}).Count(&total)

	return products, total, nil
}
